import { useEffect, useReducer } from "react"

const reducer=(state,action)=>{
    console.log(state)
    switch(action.type){
        case 'start':
            return {...state,isRunning:true}
        case 'stop':
            return{...state,isRunning:false}
            case 'reset':
              return{isRunning:false,time:0}  
        case 'tick':
            return{...state,time:state.time+1}
         default:
             return state   
    }
}

// const state1=reducer({isRunning:false,time:10},{type:'start'})

function initState(time){
    return {isRunning:false,time}
}

const Stopwatch=()=>{
    const [state,dispatch]=useReducer(reducer,0,initState)
    console.group('运行后的state')
    console.log(state)
    console.log()
    console.log(state)
    useEffect(()=>{
     if(!state.isRunning){
         return
     }
     const time= setInterval(()=>{dispatch({type:'tick'})},1000)
     return()=>{
         console.log('清楚定时器')
         clearInterval(time)    
    }
    },[state.isRunning])
    
  return(
      <div>
          {state.time}秒
          <button onClick={()=>dispatch({type:'start'})}>开始计时</button>
          <button onClick={()=>dispatch({type:'stop'})}>停止计时</button>
          <button onClick={()=>dispatch({type:'reset'})}>重置</button>
      </div>
  )
     
}
export default Stopwatch